#include "StdAfx.h"

//#include "QError.h"
#include "QWindow.h"
#include "QStatusBar.h"

using namespace micro::gui;


QStatusBar::QStatusBar(void)
{
}

QStatusBar::~QStatusBar(void)
{
}


void QStatusBar::SetPartText(int iPart, QString str, UINT Style) 
	// Available Styles: Combinations of ...
	//0					The text is drawn with a border to appear lower than the plane of the window.
	//SBT_NOBORDERS		The text is drawn without borders.
	//SBT_OWNERDRAW		The text is drawn by the parent window.
	//SBT_POPOUT		The text is drawn with a border to appear higher than the plane of the window.
	//SBT_RTLREADING	The text will be displayed in the opposite direction to the text in the parent window.
{
	if (IsWindow())
	{
		if (SendMessage( SB_GETPARTS, 0L, 0L) >= iPart)
		{
			if (!SendMessage(SB_SETTEXT, iPart | Style, (LPARAM)(LPTSTR)str))
				throw QError(_T("Failed to set status bar text"));
		}
	}
}



void QStatusBar::SetPartWidth(int iPart, int iWidth) 
{
		// This changes the width of an existing pane, or creates a new pane
		// with the specified width

		int* iPartWidths = nullptr;
		int* iNewPartWidths = nullptr;

		try
		{
			if (IsWindow())
			{
				if ((iPart > 256) || (iWidth < 0))
					throw QError (_T("CStatusbar::SetPartWidth ... Invalid parameters"));

				if (iPart < 0) iPart = 0;

				int iParts = (int)SendMessage( SB_GETPARTS, 0L, 0L);
				iPartWidths = new int[iParts];

				// Some MS compilers (including VS2003 under some circumstances) return nullptr instead of throwing
				//  an exception when new fails. We make sure an exception gets thrown!
				if (nullptr == iPartWidths)
					throw QError (_T("Alloc error"));


				SendMessage(SB_GETPARTS, iParts, (LPARAM)iPartWidths);

				int iNewParts = max(iPart+1, iParts);
				iNewPartWidths = new int[iNewParts];
				if (nullptr == iNewPartWidths)
					throw QError(_T("Alloc error"));


				ZeroMemory(iNewPartWidths, iNewParts*sizeof(int));

				for (int i = 0; i < iParts; ++i)
					iNewPartWidths[i] = iPartWidths[i];

				if (0 == iPart)
					iNewPartWidths[iPart] = iWidth;
				else
					iNewPartWidths[iPart] = iNewPartWidths[iPart -1] + iWidth;

				if (! SendMessage( SB_SETPARTS, iNewParts, (LPARAM)iNewPartWidths))
					throw   QError (_T("CStatusbar::SetPartWidth failed"));

				delete []iNewPartWidths;
				delete []iPartWidths;
			}
		}

		catch (QError &e)
		{
			if (iNewPartWidths) delete []iNewPartWidths;
			if (iPartWidths)	delete []iPartWidths;

			e.PrintMessage();
			//DebugErrMsg(_T("Exception in CStatusbar::SetPartWidth"));
		}

		catch (...)
		{
			if (iNewPartWidths) delete []iNewPartWidths;
			if (iPartWidths)	delete []iPartWidths;
			QError e;
			e.PrintMessage();
		}
}